<script lang="ts" setup>
import { useHomeStore, useAuthStore } from '@/store'
import file from '@/api/file'
import { getEnv } from '@/utils/shared.ts'

const emits = defineEmits(['uploaded'])
const { modifyStore, modifyStoreType, fileType42ImageList } = storeToRefs(useHomeStore())
const { token, sessionid } = storeToRefs(useAuthStore())
const uploadUrl = ref(getEnv().apiBase + '/napFileApi/merchant/common/file/upload')
const fileList = ref<any[]>([])
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
})

onMounted(() => {
  if (fileType42ImageList.value.length !== 0) {
    fileType42ImageList.value.forEach(async (img: any) => {
      img.status = 'uploading'
      img.message = '载入中'
      fileList.value.push(img)
      img.url = await file.downloadImage(img.name, '3')
      img.status = 'success'
    })
  }
})
const formHeader = {
  'Content-Type': 'form-data',
  'X-Authorization': token.value,
}
const originFormData = {
  sessionid: sessionid.value,
  businessId: modifyStore.value.storeId,
  refType: '42',
  bindingType: '3',
}

function getRefIds(refIds) {
  // 输入验证：检查 refIds 是否为数组且不为空
  if (!Array.isArray(refIds) || refIds.length === 0) {
    return "无效的 refIds 输入";
  }

  for (const refId of refIds) {
    const file = fileType42ImageList.value.find(file => file.refId === refId.toString());
    if (!file) {
      return refId.toString();
    }
  }
  // 如果所有 refIds 都已找到，则返回最后一个 refId 或特定值
  return refIds[refIds.length - 1].toString(); // 或根据需要返回特定值
}

function getRefId() {
  console.log("fileType42ImageList.value")
  console.log(fileType42ImageList.value)
  const file1 = fileType42ImageList.value.find(file => file.refId === '1')
  if (file1) {
    const file2 = fileType42ImageList.value.find(file => file.refId === '2')
    if (file2) {
      const file3 = fileType42ImageList.value.find(file => file.refId === '3')
      if (file3) {
        const file4 = fileType42ImageList.value.find(file => file.refId === '4')
        if (file4) {
          const file5 = fileType42ImageList.value.find(file => file.refId === '5')
          if (file5) {

          } else {
            return '5'
          }
        } else {
          return '4'
        }
      } else {
        return '3'
      }
    } else {
      return '2'
    }
  } else {
    return '1'
  }
}

async function beforeUpload (UploadFile: any, options: any) {
  // UploadFile  是 uni.uploadFile ， 你也可以自定义设置其它函数
  console.log('/file/upload')
  const refIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
  const refId = getRefIds(refIds);
  const formData = Object.assign(options.formData, { refId })
  console.log('Request FormData')
  console.log(formData)
  UploadFile({
    url: options.url,
    filePath: options.filePath,
    fileType: options.fileType,
    header: {
      'Content-Type': 'multipart/form-data',
      'X-Authorization': token.value,
      ...options.headers
    },
    formData,
    name: options.name,
    success(response: { errMsg: any; statusCode: number; data: string }) {
      if (options.xhrState == response.statusCode) {
        options.onSuccess?.(response, options);
      } else {
        options.onFailure?.(response, options);
      }
    },
    fail(e: any) {
      options.onFailure?.(e, options);
    }
  });
} 

function uploadSuccess({ responseText }: {responseText: any}) {
  if (responseText.statusCode === 200) {
    const data = JSON.parse(responseText.data)
    console.log('Response')
    console.log(data)
    if (data.status === 'success') {
      fileType42ImageList.value.push(Object.assign(data.data, {
        name: data.data.imageId,
        url: '',
        status: 'ready',
        message: '上传成功',
        type: 'image',
      }))
    }
  }
}

async function deleteImage ({index}: {index: string}) {
  const currentFile = fileType42ImageList.value[index]
  const { data } = await file.delImage(currentFile.name,'3')
  if (data.status === 'success') {
    uni.showToast({
      icon: 'success',
      title: data.message
    })
    fileType42ImageList.value.splice(index, 1)
  }
}

function validate() {
  return new Promise((resolve) => {
    resolve(modifyStoreType.value === 'update' || fileList.value.length !== 0)
  })
}

defineExpose({ validate })
</script>

<template>
  <div class="propt-loader">
    <nut-uploader
      v-model:file-list="fileList"
      :source-type="['camera']"
      :url="uploadUrl"
      :data="originFormData"
      :headers="formHeader"
      :maximum="15"
      :before-upload="beforeUpload"
      with-credentials="true"
      @success="uploadSuccess"
      @delete="deleteImage"
      :is-deletable="!props.disabled"
      :disabled="props.disabled"
    />
  </div>
</template>
